﻿using System;
using System.Text;
using System.Configuration;
using System.Data;
using System.Xml;
using System.IO;

namespace CommonUtil
{
    public class AppConfig
    {
        #region config文件
        #region 1.读取的配置信息项
        public static string GetAppSetting(string Key)
        {
            return ConfigurationManager.AppSettings[Key];
        }
        public static string GetConnectionString(string Name)
        {
            return ConfigurationManager.ConnectionStrings[Name].ConnectionString;
        }
        #endregion 读取的配置信息项

        #region 2.添加的配置信息项
        public static void AddAppSetting(string Key, string Value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Add(Key, Value);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        public static void AddConnectionString(string Name, string connectionString)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringSettings css = new ConnectionStringSettings(Name, connectionString, "System.Data.SqlClient");
            config.ConnectionStrings.ConnectionStrings.Add(css);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        #endregion 添加的配置信息项

        #region 3.修改的配置信息项
        public static void SetAppSetting(string Key, string Value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings[Key].Value = Value;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        public static void SetConnectionString(string Name, string connectionString)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings[Name].ConnectionString = connectionString;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }        
        #endregion 修改的配置信息项

        #region 4.删除配置信息项
        public static void DelAppSetting(string Key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove(Key);
            config.Save(ConfigurationSaveMode.Modified);
        }
        public static void DelConnectionString(string Name)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove(Name);            
            config.Save(ConfigurationSaveMode.Modified);
        }
        #endregion 删除的配置信息项
        #endregion config文件

        #region cofig文件配置信息完整性检查
        #endregion

        public static string[] GetAppSettings(int valCount)
        {
            if (valCount <= 10)
                valCount = 10;
            string[] values = new string[valCount];
            int count = 0;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                values[count] = ConfigurationManager.AppSettings[key];
                count += 1;
            }
            return values;
        }
        public static string[] GetConnectionStrings(int valCount)
        {
            if (valCount <= 10)
                valCount = 10;
            string[] values = new string[valCount];
            int count = 0;
            foreach (string name in ConfigurationManager.ConnectionStrings)
            {
                values[count] = ConfigurationManager.ConnectionStrings[name].ConnectionString;
                count += 1;
            }
            return values;
        }

        /// <summary>
        /// 以DataTable形式
        /// 返回当前配置文件中的所有ConnectionStrings
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// 读取指定XML的所有connectionStrings，以DataTable返回
        /// Name,ZhangTao,ConnString
        /// </summary>
        /// <param name="AppName"></param>
        /// <returns></returns>
        public static DataTable GetDTConnectionStrings(string AppName)
        {
            DataTable dt = null;
            string path = AppDomain.CurrentDomain.BaseDirectory + "//" + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                xNode = xDoc.SelectSingleNode("//connectionStrings");

                dt = new DataTable(Guid.NewGuid().ToString());
                dt.Columns.Add("Name", System.Type.GetType("System.String"));
                dt.Columns.Add("ZhangTao", System.Type.GetType("System.String")); //
                dt.Columns.Add("ConnString", System.Type.GetType("System.String"));

                foreach (XmlNode node in xNode.ChildNodes)
                {
                    DataRow dr = dt.NewRow();
                    dr["Name"] = node.Attributes["name"].Value;
                    dr["ZhangTao"] = node.Attributes["zhangtao"].Value;
                    dr["ConnString"] = DESEncrypt.DecryptDES(node.Attributes["connectionString"].Value);
                    //dr["ConnectionString"] = node.Attributes["connectionString"].Value;
                    dt.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }

        #region xml文件
        #region 1.读xml
        /// <summary>
        /// 读取xml的appSettings配置项
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="AppName">AppName.exe.config</param>
        /// <returns></returns>
        public static string GetAppSetting(string Key, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + Key + "']");
                if (xElem != null)
                    return xElem.GetAttribute("value");
                else
                    return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
        /// <summary>
        /// 读取xml的connectionStrings配置项
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="AppName">AppName.exe.config</param>
        /// <returns></returns>
        public static string GetConnectionString(string Name, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//connectionStrings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@name='" + Name + "']");
                if (xElem != null)
                    return xElem.GetAttribute("connectionString");
                else
                    return "";
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static string GetZhangTaoString(string Name, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//connectionStrings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@name='" + Name + "']");
                if (xElem != null)
                    return xElem.GetAttribute("zhangtao");
                else
                    return "";
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 读取指定XML的所有connectionStrings，以DataTable返回
        /// Name,ZhangTao,ConnString
        /// </summary>
        /// <param name="AppName"></param>
        /// <returns></returns>
        public static DataTable GetDTConnectionStringsEx(string FilePath)
        {
            DataTable dt = null;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                if (File.Exists(FilePath))
                {
                    xDoc.Load(FilePath);
                    XmlNode xNode;
                    xNode = xDoc.SelectSingleNode("//connectionStrings");

                    dt = new DataTable(Guid.NewGuid().ToString());
                    dt.Columns.Add("Name", System.Type.GetType("System.String"));
                    dt.Columns.Add("ZhangTao", System.Type.GetType("System.String")); //
                    dt.Columns.Add("ConnString", System.Type.GetType("System.String"));

                    foreach (XmlNode node in xNode.ChildNodes)
                    {
                        DataRow dr = dt.NewRow();
                        dr["Name"] = node.Attributes["name"].Value;
                        dr["ZhangTao"] = node.Attributes["zhangtao"].Value;
                        dr["ConnString"] = DESEncrypt.DecryptDES(node.Attributes["connectionString"].Value);
                        //dr["ConnectionString"] = node.Attributes["connectionString"].Value;
                        dt.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                dt = null;
                throw ex;
            }
            return dt;
        }

        public static string GetDTConnectionStringsArray(DataTable dt)
        {
             string connStrings = string.Empty;
            if (dt.Rows.Count > 0)
            {
                //dr["Name"]
                //dr["ZhangTao"]
                //dr["ConnString"] 
                foreach (DataRow dr in dt.Rows)
                {
                    connStrings = connStrings + dr["ZhangTao"].ToString() + "|" + dr["ConnString"].ToString() + ",";
                }
                connStrings = connStrings.TrimEnd(',');
            }
            return connStrings;
        }
        #endregion 

        #region 2.写xml
        /// <summary>
        /// 修改xml的appSettings配置项
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="AppName">AppName.exe.config</param>
        /// <returns></returns>
        public static void SetAppSetting(string Key, string Value, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "//" + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + Key + "']");
                xElem.SetAttribute("value", Value);
                xDoc.Save(path);
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 修改xml的connectionStrings配置项
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="connectionString">AppName.exe.config</param>
        /// <param name="AppName"></param>
        public static void SetConnectionString(string Name, string ZhangTao,string connectionString, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//connectionStrings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@Name='" + Name + "']");
                xElem.SetAttribute("zhangtao", ZhangTao);
                xElem.SetAttribute("connectionString", connectionString);
                xDoc.Save(path);
            }
            catch (Exception)
            {
            }
        }
        #endregion

        public static void AddConnectionString(string Name, string ZhangTao, string connectionString, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory  + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode = xDoc.SelectSingleNode("//connectionStrings");
                XmlElement xElem = xDoc.CreateElement("add");                
                xElem.SetAttribute("name", Name);
                xElem.SetAttribute("zhangtao", ZhangTao);
                xElem.SetAttribute("connectionString", connectionString);
                xNode.AppendChild(xElem);
                xDoc.Save(path);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void DeleteConnectionString(string Name, string AppName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + AppName;
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//connectionStrings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@name='" + Name + "']");
                if (xElem != null)
                {
                    xElem.ParentNode.RemoveChild(xElem);
                    //xElem.RemoveAll();
                }
                xDoc.Save(path);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion xml文件
    }
}